<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\common\library\Upload;
use think\Db;
use app\index\controller\Toolposter;

class Tool extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $type_img = [
                        1=>['name'=>'1小学教师.jpg','date_wz'=>[1025,3120],'erweim_wz'=>[980,2730],'erweim_size'=>350],
                        2=>['name'=>'2小学.jpg','date_wz'=>[1025,3105],'erweim_wz'=>[980,2630],'erweim_size'=>450],
                        3=>['name'=>'3高考.jpg','date_wz'=>[1040,3175],'erweim_wz'=>[1060,2810],'erweim_size'=>350],
                    ];
    public $type_kemu = [
                    1=>['name'=>'文科','local'=>[1175,450]],
                    2=>['name'=>'理科','local'=>[1175,450]],
                    3=>['name'=>'新高考','local'=>[1145,450]],
                ];    
    public $type_nainji = [
                    1=>['name'=>'一年级','local'=>[1145,460]],
                    2=>['name'=>'二年级','local'=>[1145,460]],
                    3=>['name'=>'三年级','local'=>[1145,460]],
                    4=>['name'=>'四年级','local'=>[1145,460]],
                    5=>['name'=>'五年级','local'=>[1145,460]],
                    6=>['name'=>'六年级','local'=>[1145,460]],
                ];
    public $url_img = ROOT_PATH.'public/tool/jiangzuo/';

   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $Api = new Api();
        //获取默认值
        $this->config = $Api->getConfig($Api->getDefault('Assistant'));
        $this->config['oauth']['callback'] = "http://oa.fc62.com/index/tool/login";
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new \app\admin\model\tool\Lecture;
        $this->Sourcemodel = new \app\admin\model\base\Source;
       
        //退出
        //print_r($this->auth->logout());die; 
        //模拟登陆
      // $this->auth->IndexLogin('GaoZhenYu');
        //判断权限
        //print_r($this->auth->check('see/index'));die;
    }

   
    public function index($type = 'generate'){
       $this->auth->logout();
       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/tool/login/type/'.$type);
        
    }  
    /**
     * 生成苏回音
     */
    public function generate(){

       if ($this->request->isPost()){
            $params = $this->request->post();
            if ($params) {
                Db::startTrans();
                $result = $this->watermark($params);
                if(!$result){ 
                    Db::rollback();
                    $this->error("操作失败");
                }
                if($result['true']==1){
                    $arr = [];
                    $arr['userid'] = \think\Session::get('admin')['userid'];
                    $arr['type'] = $params['type'];
                    if($params['type'] == 3){
                        $arr['subject'] = $params['kemu'];
                        $arr['lecture_time'] = $params['jzdate'];
                        $arr['lecture_text'] = $params['text'];
                    }else{
                        $arr['grade'] = $params['nianji'];
                    }
                    $arr['closing_date'] = $params['date'];
                    $arr['erweima_img'] = $params['erweima'];
                    $arr['generate_img'] = $result['data'];
                    $info = $this->model->allowField(true)->save($arr);
                    if($info){
                        Db::commit();
                        $this->success('操作成功','',$result['data']);
                    }else{
                        Db::rollback();
                    }
                }else{
                    $this->error("操作失败");
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
       } 
       return $this->view->fetch();
 
    }    
    /**
     * 生成苏回音
     */
    public function watermark($arr = []){
        if(!$arr['type']) return ['true'=>0,'msg'=>'参数错误'];
        $filename = $this->url_img.$this->type_img[$arr['type']]['name'];
        //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/tool/'.date("Ymd").'/'.$arr['type'].'/'.date('YmdHis') . uniqid().'.png';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/tool/".date("Ymd")."/".$arr['type']."/".date('YmdHis') . uniqid().'.png';
        $no_url  = '/'.$imglName.'';
        //字体url
        $zitiurl = $this->url_img.'simsun.ttf';
         //二维码缩略
        $er_image = \think\Image::open(ROOT_PATH.'/public'.$arr['erweima']);
        $er_image->thumb($this->type_img[$arr['type']]['erweim_size'],$this->type_img[$arr['type']]['erweim_size'],\think\Image::THUMB_CENTER)->save(ROOT_PATH.'/public'.$arr['erweima']);
         $image = \think\Image::open($filename); //要加水印的图片
         //日期位置
         $date_wz = $this->type_img[$arr['type']]['date_wz'];
         $image->text($arr['date'],$zitiurl,40,'#17161c',$date_wz)->save($imglName);
        //二维码位置
        $erweim_wz = $this->type_img[$arr['type']]['erweim_wz'];
        $image->water(ROOT_PATH.'/public'.$arr['erweima'],$erweim_wz)->save($imglName); 
        switch ($arr['type']) {
              case 1:
                    $image->text($this->type_nainji[$arr['nianji']]['name'],$zitiurl,45,'#060610',$this->type_nainji[$arr['nianji']]['local'])->save($imglName);
                  break;
              case 2:
                    $image->text($this->type_nainji[$arr['nianji']]['name'],$zitiurl,45,'#060610',$this->type_nainji[$arr['nianji']]['local'])->save($imglName);
                break;
            case 3:
                    $image->text($this->type_kemu[$arr['kemu']]['name'],$zitiurl,45,'#060610',$this->type_kemu[$arr['kemu']]['local'])->save($imglName);
                    //内容位置
                    $text_wz=[300,1830];
                    $image->text('    讲座时间：'.$arr['jzdate'],$zitiurl,40,'#17161c',$text_wz,0,0,1905)->save($imglName);//内容位置
                    $text_wz=[300,1895];
                    $image->text('    '.$arr['text'],$zitiurl,40,'#17161c',$text_wz,0,0,1905)->save($imglName);
                    
                break;
            
            default:
                # code...
                break;
        }
        return ['true'=>1,'msg'=>'操作成功','data'=>$no_url];
 
    }
 
    /**
     * 测试
     */
    public function test($arr = []) {
        echo "<textarea></textarea>";
        $peizhi = $this->type_img[2];
        $filename = $this->url_img.$peizhi['name'];
        //设置路径目录信息
        $url = ROOT_PATH . 'public/uploads/tool/'.date("Ymd").'/2/'.time().'.png';  
        $dir_name = dirname($url);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $imglName = "uploads/tool/".date("Ymd")."/2/".time().'.png';
        $no_url  = ''.request()->domain().'/'.$imglName.'';
        $wenke=array(1145,460);
        $image = \think\Image::open($filename); //要加水印的图片
        $image->text('一年级',$this->url_img.'simsun.ttf',45,'#060610',$wenke)->save($imglName);
         // $wz=array(310,1830);
         // $image->text('    讲座时间：2月20日、21日、22日、23日每晚8~9点。讲座时间：2月20日',$this->url_img.'simsun.ttf',40,'#222125',$wz,0,0,1905)->save($imglName);
         //   $wz=array(310,1895);
         // $image->text('    2月20日，语文：北京五中徐春老师主讲；2月21日，英语：北京171中学秦建鹏老师主讲；2月22日，数学：北京五中熊丹老师主讲；冲刺阶段对策讲座：全科资讯梁星老师主讲（2月23日）全科资讯梁星老师主讲（2月全科资讯梁星老',$this->url_img.'simsun.ttf',40,'#222125',$wz,0,0,1905)->save($imglName);
        $wz=$peizhi['date_wz'];
        $image->text('2月10日前',$this->url_img.'simsun.ttf',40,'#17161c',$wz)->save($imglName);
         $wz=$peizhi['erweim_wz'];
         //二维码缩略
         $er_image = \think\Image::open($this->url_img.'er.jpg');
        // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
         $er_image->thumb(450,450,\think\Image::THUMB_CENTER)->save($this->url_img.'er.jpg');
        $image->water($this->url_img.'er.jpg',$wz)->save($imglName); 
        echo'<img src="'.$no_url.'" height="900">';die;
    }
    public function recruit(){
        if ($this->request->isPost()){
            $params = $this->request->post();
            if ($params) {
             
               Db::startTrans();
               $row = $this->Sourcemodel->where(['name'=>$params['name']])->find();
               if($row){
                  Db::rollback();
                  switch ($params['typexz']) {
                    case 1:
                      $this->error("来源已经存在,是否跳转",'',$row['erweima_url']);
                      break;
                    case 2:
                      $this->error("来源已经存在,是否跳转",'',$row['erweima_url']);
                      break;
                    case 3:
                      $this->error("来源已经存在,是否跳转",'','/index/tool/recruit_success/ids/'.$row['id']);
                      break;
                    default:
                      # code...
                      break;
                  }
                  if($params['typexz'] == 1){
                      $this->error("来源已经存在,是否跳转",'',$row['erweima_url']);
                  }else{
                      $this->error("来源已经存在,是否跳转",'',$row['poster_url']);
                  }
                  
               }
                $params['publish'] = 1;
                $params['z_publish'] = 1;
                $result = $this->Sourcemodel->allowField(true)->save($params);
                if($result){
                    $data = [];
                    $data['erweima_url'] = $this->make($params['type'],$this->Sourcemodel->id);
                    $data['url'] =  str_replace("xxx",$this->Sourcemodel->id,GetBaseInfo('Tool')['Source'][$params['type']]['url']);
                    $this->Toolposter = new Toolposter();
                    $resut = $this->Toolposter->watermark(['type'=>GetBaseInfo('Tool')['Source'][$params['type']]['hb_type'],'erweima'=>$data['erweima_url']]);
                    if($resut['true'] == 1){
                      $data['poster_url'] = $resut['data'];
                    }
                    $send_show = $this->Sourcemodel->where(['id'=>$this->Sourcemodel->id])->update($data);
                    if($send_show){
                      Db::commit();
                      switch ($params['typexz']) {
                        case 1:
                         $this->success("操作成功",'',$data['erweima_url']);
                          break;
                        case 2:
                          $this->success("操作成功",'',$data['poster_url']);
                          break;
                        case 3:
                          $this->success("操作成功",'','/index/tool/recruit_success/ids/'.$this->Sourcemodel->id);
                          break;
                        default:
                          # code...
                          break;
                      }
                      $this->success('操作成功','',$data);
                    }else{
                       Db::rollback();
                     $this->error("操作失败");
                    }
                }else{
                    Db::rollback();
                    $this->error("操作失败");
                }
               
            }
            $this->error(__('Parameter %s can not be empty', ''));
       } 
       return $this->view->fetch();
    }
    public function recruit_success($ids = null){
        if(!$ids)  $this->error("参数错误");
        $row = $this->Sourcemodel->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $this->view->assign('row',$row);
        return $this->view->fetch();

    }
     /**
     * 生成二维码
     * @return [type] [description]
     */
    public function make($type = 1,$ids = null){
        $fxurl = str_replace("xxx",$ids,GetBaseInfo('Tool')['Source'][$type]['url']);
        $url ='http://qr.liantu.com/api.php?logo=https://oa.fc62.com/uploads/qr/qr.png&text='.$fxurl;
        $erwema = update_url($url,"/uploads/tool/erweima/".date("Ymd")."/source/");
        return $erwema;
    }
    public function login($type = 'generate'){
        $app = Factory::work($this->config);
        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;
                  switch ($type) {
                    case 'generate':
                      $url = $this->request->domain().'/index/tool/generate';
                      break;
                    case 'recruit':
                      $url = $this->request->domain().'/index/tool/recruit';
                      break;
                    default:
                      # code...
                      break;
                  }
                 return redirect($url);
                }
            }
        }else{
            return redirect($this->request->domain().'/index/tool/oauth/type/'.$type);
        }
    }
   public function oauth($type = 'generate'){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."/type/".$type."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }
     public function upload(){
        //是否有图片上传
        if ($this->request->request('file')) {
            $upload = new Upload();
            $upload->path(ROOT_PATH.'public/uploads/tool/erweima');//上传 发货凭证
            $file = $upload->upbase($this->request->request('file'),'/uploads/tool/erweima/');
            if($file){
                 $this->success('操作成功','',$file);
            }else{
                 $this->error($upload->error());
            }
        }
    }
  

}
